<?php


namespace api\app\middleware;


use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class CheckToken
{
    //解密token，使用用户ID
    public function handle($request, \Closure $next)
    {
        //接收token
        $token = request()->header();
        //判断
        if (!isset($token) || empty($token['token'])) {
            return json([
                'code' => 0,
                'msg' => 'token 错误'
            ]);
        }
        //解密
        $key = new Key(config('app.jwt_key'),'HS256');
        try {
            $res = JWT::decode($token['token'],$key);

        } catch (\Exception $exception){
            return json([
                'code' => 0,
                'msg' => $exception->getMessage()
            ]);
        }
        $id = $res->data->user_id;
        $request->token = $id;
        return $next($request);

    }

}